package com.example.kaogong.common.utils;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: 七牛云工具类
 * @author: 徐文升
 * @create: 2022-03-28 17:26
 **/
@Component
public class QiniuUtil {
    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    public String generateUploadToken(String fileName) {
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(bucket, fileName);
        return uploadToken;
    }

    public String generateDownloadUrl(String key) {
        DownloadUrl url = new DownloadUrl(domain, false, key);
        String buildURL = null;
        try {
            buildURL = url.buildURL();
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return buildURL;
    }

    public void deleteFile(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}